import re

class CountPatt:
    def __init__(self, fname):
        self.fname = fname

    def count_patt(self, patt):
        result = {}  # 用于保存结果的变量

        # 为了有更好的匹配效率，将正则表达式模式进行编译
        cpatt = re.compile(patt)
        with open(self.fname) as fobj:
            for line in fobj:
                m = cpatt.search(line)
                if m:   # 任何非空对象都是真
                    key = m.group()
                    result[key] = result.get(key, 0) + 1

        return result

if __name__ == '__main__':
    logfile = 'access_log'
    ip = '^(\d+\.){3}\d+'  # 1234.5678.1.23  192.168.3.50
    br =  'Chrome|Firefox|MSIE'
    cp1 = CountPatt(logfile)
    result1 = cp1.count_patt(ip)
    print(result1)
    result2 = cp1.count_patt(br)
    print(result2)
    myos = 'Windows|Linux'
    result3 = cp1.count_patt(myos)
    print(result3)